drops = {}
needlist = {}
liststatus = {}
ITEM = 1;
PLAYER = 0;
acceptrolls = 0;

local function GetArgs(text, separator)
	local args = {}
	local i = 0
	for value in string.gmatch(text, "[^"..separator.."]+") do
		i = i + 1
		args[i] = value
	end	
	return args
end

function ELoot_SlashHandler(msg)
	local msgargs = GetArgs(msg," ");
	if (msg=="") then
		--DEFAULT_CHAT_FRAME:AddMessage("***LFGVoyeur Help***")
		--DEFAULT_CHAT_FRAME:AddMessage("/lfgv ...")
		--DEFAULT_CHAT_FRAME:AddMessage("  show   = Show main window")
		--DEFAULT_CHAT_FRAME:AddMessage("  reset  = Reset window and restart UI")
		--DEFAULT_CHAT_FRAME:AddMessage("  normal = Normal instances only")
		--DEFAULT_CHAT_FRAME:AddMessage("  heroic = Heroic instances only")
		--DEFAULT_CHAT_FRAME:AddMessage("  both   = Normal and heroic instances both")
		--DEFAULT_CHAT_FRAME:AddMessage("  min    = Set minimum players per instance (currently " .. LFGVoyeur_Min .. ")")
	end

	if (msgargs[1]=="query") then
		DEFAULT_CHAT_FRAME:AddMessage("ELoot: " .. msgargs[2] .. " has " .. ELoot_QuerySinglePlayer(msgargs[2]) .. " dkp");
	end
	
	if (msg=="drops") then
		DEFAULT_CHAT_FRAME:AddMessage(drops[1]); -- "<-ELoot-> Current drops: " .. 
	end
	
	if (msg=="open") or (msg=="show") then
		KarmaRollFrame:Show();
	end
	
	if (msgargs[1]=="manualadd") then
		local links = ProcessLinks(msg);
		_, itemLink, _, _, _, _, _, _, _, _ = GetItemInfo(links[1])
		tinsert(drops, itemLink);
		if (IsItemInDropTable(itemLink) == true) then
			local playerClass, _ = UnitClass("player");
			local dkp = ELoot_QuerySinglePlayer(UnitName("player"));
			if (dkp == nil) then dkp = "0"; end
			tinsert(needlist, itemLink .. " " .. UnitName("player") .. " " .. playerClass .. " " .. "ClassLeader " .. dkp .. " " .. "-");
			DEFAULT_CHAT_FRAME:AddMessage("<-ELoot-> You have been added to the needlist for " .. itemLink);
			ELoot_List_Update();
		else
			DEFAULT_CHAT_FRAME:AddMessage("<-ELoot-> " .. itemLink .. " wasn't found on the droplist");
		end
	end
end

function ELoot_GetDkpInfoFromStringForQuery(str)
	if not str then
		return nil;
	elseif string.find(str, "%d%d/%d%d/%d%d %d%d:%d%d:%d%d") then
		return nil;
	end
	
	local dkp_pattern = string.gsub("(%-?%d+)", string.gsub("(%-?%d+)", "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1"), string.gsub("(%-?%d+%.%d%d)", "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") );
	local s, e, dkp = string.find(str, dkp_pattern);

	if not s then
		s, e, dkp = string.find( str, "(%-?%d+)");
	end

	return dkp;
end

function ELoot_QuerySinglePlayer(query_name)
	local found = false;
	local player_dkp = nil;
	local query_name_lower = string.lower(query_name);

	for i=1, GetNumGuildMembers(true) do
		local name, rank, rank_index, level, class, zone, note, officer_note, online, status = GetGuildRosterInfo(i);

		if not name then
			break;
		end

		local dkp = ELoot_GetDkpInfoFromStringForQuery(officer_note);
		local name_lower = string.lower(name);

		if name_lower == query_name_lower then
			found = true;
			player_dkp = dkp;
		end
	end

	if found then
		return player_dkp;
	else
		-- Not in the same guild
		return 0;
	end
end

function ItemIdInDropTable(iteminfo)
	if (#drops > 0) then
		for i = 1, #drops, 1 do 
			if (iteminfo == drops[i]) then 
				return i; 
			end
		end
	else
		return 0;
	end
end

function IsItemInDropTable(iteminfo)
	if (#drops > 0) then
		for i = 1, #drops, 1 do 
			if (iteminfo == drops[i]) then 
				return true; 
			end
		end
		return false;
	else
		return false;
	end
end

function GetTempNeedList(itemlink)
	local numNeeders = #(needlist);
	local TempNeedList = {}
	for i = 1, numNeeders, 1 do
		local links = ProcessLinks(needlist[i]);
		_, itemLink, _, _, _, _, _, _, _, _ = GetItemInfo(links[1])
		if (itemLink == itemlink) then 
			tinsert(TempNeedList, needlist[i]);
		end
	end
	return TempNeedList;
end

function ProcessLinks(text)
	local links = {};
	local i = 1;
	if ( text ) then
		local link, name;
		for link, name in string.gmatch(text, "|c%x+|H(item:[-%d:]+)|h%[(.-)%]|h|r") do
			if (link and name and name ~= "") then
				links[i] = link;
				i = i + 1;
			end
		end
	end
	return links;
end

function ELoot_Roll(player_name, player_roll)
  local player=string.lower(player_name);
-- If it's an open (no bonus declaration required) roll then add them to the list when they /roll
  if (OpenRoll) then
    if (KarmaList[Raid_Name][string.lower(player_name)] == nil) then
      Karma_Newplayer(player_name);
    end
    KarmaRoll_AddPlayer(player_name, false)
  end

  for i=1, #(RollList) do
    if (string.lower(RollList[i][1]) == player) then
      RollList[i][4] = tonumber(player_roll);
      RollList[i][5] = RollList[i][3] + RollList[i][4];
      break;
    end
  end

  KarmaRollList_Update();
end

function ELoot_Eventhandler(event)
	if (event == "LOOT_OPENED") then
		local lootmethod, masterlooterPartyID, masterlooterRaidID = GetLootMethod()
		--if (lootmethod == "master") then
			local LootThreshold = GetLootThreshold(); -- 3 er rare og 4 er epic
			local numItems = GetNumLootItems();
			for i = 1, numItems, 1 do 
				if (LootSlotIsItem(i)) then
					local iteminfo = GetLootSlotLink(i);
					local lootIcon, lootName, lootQuantity, rarity = GetLootSlotInfo(i); 
					--local itemName, itemLink, itemRarity, itemLevel, itemMinLevel, itemType, itemSubType, itemStackCount, itemEquipLoc = GetItemInfo(link)
					--if ((rarity >= LootThreshold) and (not IsInDropTable(iteminfo))) then
						drops[(#drops)+1] = iteminfo;
						SendChatMessage("<-ELoot-> Drop from " .. UnitName("target") .. ": " .. iteminfo, "RAID", GetDefaultLanguage("player"))
					--end
				end
			end
			ELoot_List_Update();

			--for i = 1, GetNumRaidMembers() do
			--	if GetMasterLootCandidate(i) then
			--		DEFAULT_CHAT_FRAME:AddMessage("ELoot: "..i.." -> "..GetMasterLootCandidate(i))
			--	end
			--end
		--end
	end
	
	if (event == "CHAT_MSG_WHISPER") then
		local argum = GetArgs(arg1," ")
		if (argum[1] == "!eloot") then 
			local links = ProcessLinks(arg1);
			_, itemLink, _, _, _, _, _, _, _, _ = GetItemInfo(links[1])
			if (IsItemInDropTable(itemLink) == true) then
				if (UnitInRaid(arg2) == 1) then	
					tinsert(needlist, itemLink .. " " .. arg2 .. " test1 " .. "ClassLeader " .. "81 " .. "0");
					SendChatMessage("<-ELoot-> You have been added to the needlist for " .. itemLink, "WHISPER", GetDefaultLanguage("player"), arg2);
					ELoot_List_Update();
				else
					SendChatMessage("<-ELoot-> You aren't in the raid group", "WHISPER", GetDefaultLanguage("player"), arg2);
				end
			else
				SendChatMessage("<-ELoot-> " .. itemLink .. " wasn't found on the droplist", "WHISPER", GetDefaultLanguage("player"), arg2);
			end
		end
	end
	
	if (acceptrolls ~= 0 and event == "CHAT_MSG_SYSTEM" and string.find(arg1, "rolls") and string.find(arg1, "%(1%-100%)")) then 
    _, _, player_name, player_roll = string.find(arg1, "(.+) rolls (%d+)");
    if (player_name ~= nil and player_roll ~= nil) then
      ELoot_Roll(player_name, player_roll);
    end
  end 
end

function ELoot_List_Update()
	local numDrops = #(drops);
	local ButtonIndex = 0;
	for i=1, numDrops do
		ButtonIndex = ButtonIndex + 1;
		local iteminfo = drops[i]
		if (iteminfo ~= nil) then
			getglobal("ELootButton"..ButtonIndex.."Name"):SetText(iteminfo);
			liststatus[ButtonIndex] = ITEM;
			local TempNeedList = GetTempNeedList(drops[i]);
			for j=1, #(TempNeedList) do
				ButtonIndex = ButtonIndex + 1;
				liststatus[ButtonIndex] = PLAYER;
				itemName, _, _, _, _, _, _, _, _, _ = GetItemInfo(iteminfo) 
				local itemnamearray = GetArgs(itemName, " ");
				local needstring = GetArgs(TempNeedList[j]," ");
				getglobal("ELootButton"..ButtonIndex.."Name"):SetText(needstring[(#itemnamearray)+1]);
				getglobal("ELootButton"..ButtonIndex.."Class"):SetText(needstring[(#itemnamearray)+2]);
				getglobal("ELootButton"..ButtonIndex.."Rank"):SetText(needstring[(#itemnamearray)+3]);
				getglobal("ELootButton"..ButtonIndex.."DKP"):SetText(needstring[(#itemnamearray)+4]);
				getglobal("ELootButton"..ButtonIndex.."Roll"):SetText(needstring[(#itemnamearray)+5]);
			end
		end
	end
end
